package core;

import java.util.ArrayList;
import java.util.List;

import dataStructures.*;
import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import xml.QueryWriter;
import xml.TweetWriter;

public class MyTwitter {
	public static Twitter twitter;
		public static void printQuery(Query query) {
		System.out.println("XXX: Query:" + query.getQuery() + " " + query.getGeocode());		
	}


	public static void search(MyQuery myQuery) {
		Query queryZZZ = new Query(myQuery.term);
		queryZZZ.setGeoCode(
				new GeoLocation(Double.valueOf(myQuery.location.latitude), Double.valueOf(myQuery.location.longitude)), 
				Double.valueOf(myQuery.location.radius), 
				(myQuery.location.unit.compareToIgnoreCase("true") == 0 ? Query.MILES : Query.KILOMETERS));
		
		TimeStamp now = new TimeStamp();
		
		QueryWriter queryWriter = new QueryWriter(now + "_query" + ".xml");
		queryWriter.writeQuery(new MyQuery(queryZZZ));
			  
	    QueryResult resultZZZ;
		try {
			resultZZZ = twitter.search(queryZZZ);

			TweetWriter tweetWriter = new TweetWriter(now + "_results" + ".xml");
			List<MyTweet> tweets = new ArrayList<MyTweet>();
			
		    for (Tweet tweet : resultZZZ.getTweets()) {
//		        System.out.println(
//		        		tweet.getCreatedAt() + 
//		        		" user: " + tweet.getFromUser().substring(0, 2) +
//		        		" text: " + tweet.getText().substring(0, 2) +
//		        		" loc: " + tweet.getGeoLocation()
//		        );
		        tweets.add(new MyTweet(tweet));
		    }
		    tweetWriter.writeTweets(tweets);
		} catch (TwitterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public static Twitter login(String username, String password) {
		twitter = new TwitterFactory().getInstance(username, password);
		return twitter;
	}
}
